package com.fjzn.detect.start.user;

import cn.hutool.core.bean.BeanUtil;
import com.fjzn.detect.core.result.ResponseResult;
import com.fjzn.detect.start.user.model.LoginBody;
import com.fjzn.detect.start.user.model.UserInfo;
import com.fjzn.detect.repository.user.entity.SysUser;
import com.fjzn.detect.service.security.LoginUser;
import com.fjzn.detect.service.security.SysLoginService;
import com.fjzn.detect.service.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户登录及用户信息相关控制器
 *
 * @author yzh
 * @since 2021年04月26日10:46:50
 */
@RestController
public class UserLoginController {

    @Autowired
    private SysLoginService loginService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public ResponseResult<String> login(@RequestBody LoginBody loginBody) {

        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());

        return ResponseResult.success(token);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public ResponseResult<UserInfo> getInfo() {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();

        UserInfo userInfo = BeanUtil.toBean(user, UserInfo.class);
        userInfo.setPers(loginUser.getPermissions());

        return ResponseResult.success(userInfo);
    }

    /**
     * 测试需要权限的测试
     *
     * @return 用户信息
     */
    @PreAuthorize("@permission.hasPermi('*.*.*')")
    @GetMapping("authorize")
    public ResponseResult<String> preAuthorize() {
        return ResponseResult.success("*.*.*");
    }

}
